package com.pwc;

import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class test {
  public static String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";
  public static String MY_HOST = "ldap://matlkifs1adp103.nam.ad.pwcinternal.com:389";

  public static String MY_SEARCHBASE = "CN=whuang072,OU=PwC Accounts,OU=Accounts and Groups,OU=US,DC=nam,DC=ad,DC=pwcinternal,DC=com";

  public static String MY_FILTER = "(objectclass=*)";

  public static String MY_ATTRS[] = { "sn","givenname", "mail" };

  public static void main(String args[]) throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, INITCTX);
    env.put(Context.PROVIDER_URL, MY_HOST);
    DirContext ctx = new InitialDirContext(env);
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration results = ctx.search(MY_SEARCHBASE, MY_FILTER, constraints);
    while (results != null && results.hasMore()) {
      SearchResult sr = (SearchResult) results.next();
      String dn = sr.getName() + ", " + MY_SEARCHBASE;

      System.out.println("Distinguished Name is " + dn);
      Attributes ar = ctx.getAttributes(dn, MY_ATTRS);
      if (ar == null) {
        System.out.println("Entry " + dn + " has none of the specified attributes\n");
        return;
      }
      for (int i = 0; i < MY_ATTRS.length; i++) {
        Attribute attr = ar.get(MY_ATTRS[i]);
        if (attr == null) {
          continue;
        }
        System.out.println(MY_ATTRS[i] + ":");
        for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
          System.out.println("\t" + vals.nextElement());

        }
      }
    }
  }
}
